frappe.call({
    method: "zelin_export_excel_template.api.get_export_excel_template"
})
.then((r) => {
    if (!r.exc && r.message && r.message.length) {
        let uniqueDoctypes = [...new Set(r.message.map(item => item.reference_doctype))];
        uniqueDoctypes.forEach((dt) => {
            frappe.ui.form.on(dt, {
                refresh: function(frm) {
                    let data = r.message.filter(item => item.reference_doctype === dt);
                    
                    if (frappe.model.can_print(frm.doctype) && !frm.is_new()) {
                        // 1. 创建 PDF 下拉菜单
                        let pdfDropdown = {
                            label: __("Export PDF"),
                            items: []
                        };
                        
                        // 2. 创建 Excel 下拉菜单
                        let excelDropdown = {
                            label: __("Export Excel"),
                            items: []
                        };
                        
                        // 3. 收集所有模板
                        data.forEach(d => {
                            if (d.enable_export_pdf) {
                                pdfDropdown.items.push({
                                    label: __(d.template_name),
                                    action: () => handleExport(frm, d, 'pdf')
                                });
                            }
                            
                            if (d.enable_export_excel) {
                                excelDropdown.items.push({
                                    label: __(d.template_name),
                                    action: () => handleExport(frm, d, 'excel')
                                });
                            }
                        });
                        
                        // 4. 添加下拉菜单到工具栏 - 修复这里的错误
                        if (pdfDropdown.items.length > 0) {
                            pdfDropdown.items.forEach(item => {
                                frm.add_custom_button(
                                    item.label, 
                                    item.action, // 这里传递正确的action函数
                                    pdfDropdown.label // 相同分组名称
                                );
                            });
                        }
                        
                        if (excelDropdown.items.length > 0) {
                            excelDropdown.items.forEach(item => {
                                frm.add_custom_button(
                                    item.label, 
                                    item.action, // 正确的action函数
                                    excelDropdown.label // 相同分组
                                );
                            });
                        }
                    }
                }
            });
        });
    }
});

function handleExport(frm, template, type) {
    const apiUrl = type === 'pdf' 
      ? '/api/method/zelin_export_excel_template.api.export_pdf'
      : '/api/method/zelin_export_excel_template.api.export_data';
    
    if (template.is_multi_language) {
      const dialog = new frappe.ui.Dialog({
        title: __('Select Language'),
        fields: [{
          fieldtype: "Link",
          options: "Language",
          default: frappe.boot.lang,
          label: __("Language"),
          reqd: 1,
          fieldname: "language"
        }],
        primary_action: (values) => {
          open_url_post(apiUrl, {
            doc: frm.doc,
            template_file: template.template_file,
            template_name: template.template_name,
            export_file_name: template.export_file_name || "",
            language: values.language
          });
          dialog.hide();
        },
        primary_action_label: __(`Export ${type.toUpperCase()}`)
      });
      dialog.show();
    } else {
      open_url_post(apiUrl, {
        doc: frm.doc,
        template_file: template.template_file,
        export_file_name: template.export_file_name || "",
        template_name: template.template_name
      });
    }
}